<html>
<head>

<title>Groovy Goodness: Change Scope Script Variable with Field Annotation</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Change Scope Script Variable with Field Annotation</h3>

<div class="post">
<p>The scope of a script variable changes once we add a type definition to the variable. Then the variable is no longer visible in methods of the script. To make a type variable visible in the entire script scope we add the annotation <code>@Field</code>. This way the variable has a type and can be used in methods of the script.</p>
<pre class="brush:groovy">
import groovy.transform.Field

String stringValue = 'I am typed without @Field.'
def i = 42
@Field String stringField = 'I am typed with @Field.'
counter = 0 // No explicit type definition.

def runIt() {
    try {
        assert stringValue == 'I am typed without @Field.'
    } catch (e) {
        assert e instanceof MissingPropertyException
    }
    try {
        assert i == 42
    } catch (e) {
        assert e instanceof MissingPropertyException
    }
    
    assert stringField == 'I am typed with @Field.'
    
    assert counter++ == 0
}

runIt()

assert stringValue == 'I am typed without @Field.'
assert stringField == 'I am typed with @Field.'
assert i == 42
assert counter == 1
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>